package com.sencorsta.ids.game.world.pak;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.common.service.MsgService;
import com.sencorsta.ids.common.service.MysqlService;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.game.db.RpMassage;
import com.sencorsta.ids.game.db.SettlementResult;
import com.sencorsta.ids.game.db.Wallet;
import com.sencorsta.ids.game.proto.GamePushRedPackageByProto;
import com.sencorsta.ids.game.proto.GamePushRobMoneyByProto;
import com.sencorsta.ids.game.util.PacketMoney;
import com.sencorsta.ids.game.util.PushAndSaved;
import com.sencorsta.ids.game.world.bean.Player;
import com.sencorsta.ids.game.world.bean.World;
import com.sencorsta.ids.game.world.room.WelfareRoom;
import com.sencorsta.utils.date.DateUtil;

import java.util.HashMap;
import java.util.Map;

/**
* @description: 福利红包
* @author TAO
* @date 2020/1/5 18:58
*/
public class WelfarePackage extends RedPackage implements RedisService {


    public WelfareRoom welfareRoom;

    public WelfarePackage(String sendUserId, String rpId, int count, long amount,WelfareRoom welfareRoom, long robDeposit, int roomId, boolean isRobotPack) {
        super(sendUserId, rpId, count, amount, robDeposit, roomId, isRobotPack);
        this.moneyPieces = PacketMoney.getPacketMoney(PacketMoney.getRandomWeightsList(amount, count), amount, count, 1);
        this.welfareRoom=welfareRoom;
    }

    @Override
    public void rob(Player player) {
        if (count == 0 || status != 0) {//判断红包数量
            Out.debug("红包已抢完");
            return;
        }

        if (rpResult.containsKey(player.userId)) {
            Out.debug("该红包你以领取过");
            return;
        }

        Long robAmount;//抢到的红包金额

        int index = getNextIndex();

        robAmount = moneyPieces.get(index).getMoney();//直接将剩余红包金额给最后一个人

        playerMap.put(player.userId, player);
        moneyPieces.get(index).setRobed(true);

        JSONObject result = new JSONObject();
        result.put("robUserId", player.userId);
        result.put("amount", robAmount);
        result.put("time", DateUtil.getDateTime());
        result.put("nickname", player.nickname);
        result.put("portrait", player.portrait);
        rpResult.put(player.userId, result);

        balance = balance - robAmount;

        player.onRob(rpId, -robDeposit, robDeposit);

        GamePushRobMoneyByProto.PushRobMoney.Builder push = GamePushRobMoneyByProto.PushRobMoney.newBuilder();
        push.setGameId(World.WELFARE);
        push.setRoomId(roomId);
        push.setRpId(rpId);
        push.setMoney(robAmount);
        Out.debug("福利即将为==》", player.userId, "__推送__");
        MsgService.pushBySID(PushAndSaved.pushProto(player.userId, "push.RobMoney", push), player.SID);

        if (!moneyRecode.containsKey(player.userId)) {//参与抢包用户添加recode的--防止报空
            JSONObject recode = new JSONObject();
            moneyRecode.put(player.userId, recode);
        }
        count = count - 1;

    }

    @Override
    public void update() {
        this.time -= 1;//当前包的时间减1秒
        //Out.debug("当前福利红包Id==>", rpId, "__房间为==>"+"  count==>", count, "  time==>", time);

        if (status == 0) {
            if (time == 0) {//当前包的死期已到，他妈的干掉
                if (rpResult == null) {//红包结算记录为空，代表
                    Out.debug("当前包无人问津，自动撤回");
                    status = 2;
                    Settlement();//结算
                    return;
                }
                Out.debug("当前包的死期已到，开始清算结果");
                status = 1;
                Settlement();//结算
                return;
            }

            if (count == 0) {//红包抢完了
                Out.debug("当前红包已抢完", "红包Id", rpId);
                status = 1;
                Settlement();//结算
                return;
            }
        }

    }

    @Override
    public void analysis() {

    }

    //通知结算
    public void Settlement() {
        try {

            Out.debug("------------------------通知结算福利包----rpResult----------------------------");
            Out.debug("福利红包详情：", this.toString());
            Out.debug("福利红包记录：", rpResult);


            JSONArray array = new JSONArray();
            long humanTakemoney=0;
            for (var userId : rpResult.keySet()) {
                JSONObject userRobInfo = (JSONObject) rpResult.get(userId);//得到的userId的结算记录
                long leisureAmount = userRobInfo.getLong("amount");//得到当前用户抢到的钱
                Out.debug("leisureNiuNumber-->", leisureAmount);

                JSONObject recod = moneyRecode.getJSONObject(userId);//得到当前玩家的账单记录
                recod.put("robMoney", leisureAmount);//将抢到的钱存到当前玩家的账单记录
                if (playerMap.get(userId).type!=2){
                    humanTakemoney+=leisureAmount;
                }
                array.add(Wallet.addMoneySql(playerMap.get(userId), leisureAmount, 0,roomId));
                array.add(SettlementResult.makeResult(this, recod, userId, World.WELFARE));//插入流水账单
            }
            array.add(RpMassage.updateRpMessage(rpId, 2));
            MysqlService.getInstance().executeMultipleAsyn(array);//执行sql
            R_SYSTEM.incr(WELFAREAMOUNT, humanTakemoney);//福利房散财总金额

            //Redis 红包详情入库
            niuNiuJoinRedis();
            WelfareRoom welfareRoom = (WelfareRoom) World.getInstance().games.get(World.WELFARE).rooms.get(roomId);//得到当前房间
            welfareRoom.rpPackage.remove(rpId);//内存中移除红包


            GamePushRedPackageByProto.PushRedPackage.Builder push = GamePushRedPackageByProto.PushRedPackage.newBuilder();
            push.setGameId(World.WELFARE);
            push.setRoomId(roomId);
            push.setRpId(rpId);
            for (Player current : playerMap.values()) {
                MsgService.pushBySID(PushAndSaved.pushProto(current.userId, "push.RedPackageResult", push), current.SID);
            }

        } catch (Exception e) {
            Out.error("福利结算报错");
            Out.error(this.toString());
            e.printStackTrace();
        }
    }


    //Redis 红包详情入库
    public void niuNiuJoinRedis() {
        //将红包记录插到MySql库里
        RpMassage.insertRpMessage(rpId, roomId, World.WELFARE, 2);
        Map<String, String> rpInfo = new HashMap<>();
        rpInfo.put("sendUserId", sendUserId);//发红包者
        rpInfo.put("gameId", String.valueOf(World.WELFARE));//房间Id
        rpInfo.put("roomId", String.valueOf(roomId));//房间Id
        rpInfo.put("RpId", rpId);//红包Id
        rpInfo.put("count", String.valueOf(count));//红包余数
        rpInfo.put("sumCount", String.valueOf(sumCount));//红包总个数
        rpInfo.put("amount", String.valueOf(amount));//红包金额
        rpInfo.put("balance", String.valueOf(balance));//红包余额
        rpInfo.put("moneyPieces", JSON.toJSONString(moneyPieces));//金额分配
        rpInfo.put("rpResult", String.valueOf(rpResult));//红包结果
        rpInfo.put("time", String.valueOf(time));//红包时间
        rpInfo.put("status", String.valueOf(status));//红包状态  0:发出 1:完成  2.撤回
        R_REDPACKAGE_INFO.hmset(rpId, rpInfo);
    }

}
